package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.result.R;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /*
    * 新增菜品分类/套餐分类
    * */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功！");
    }

    /*
    * 分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page pageInfo = new Page(page,pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //通过sort升序排序
        lqw.orderByAsc(Category::getSort);

        categoryService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /*
     * 根据id删除分类
     * */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /*
     * 修改分类信息
     * */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功！");
    }

    /*
     * 实现下拉显示
     * */
    @GetMapping("/list")
    public R<List<Category>> listR(Category category) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        //判断分类是否为菜品分类
        lqw.eq(category.getType() != null, Category::getType, category.getType());
        //排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lqw);

        return R.success(list);
    }
}
